import { Link } from 'react-router-dom'
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  DatePicker,
  Select,
  Popconfirm
} from 'antd'
import locale from 'antd/es/date-picker/locale/zh_CN'

import { Table, Tag, Space } from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import img404 from '@/assets/error.png'

const { Option } = Select
const { RangePicker } = DatePicker
import { useTranslation } from 'react-i18next'
import { useState } from 'react'
import { useChannel } from '@/hooks/useChannel'
import {
  articleGetListService,
  articleDeleteArticleService
} from '@/api/article'
import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'

const Article = () => {
  const navigate = useNavigate()
  const { t, i18n } = useTranslation()
  // 获取频道列表
  const { channelList } = useChannel()
  //文章列表
  const [articleList, setArticleList] = useState([])
  //请求参数
  const [reqData, setReqData] = useState({
    status: '',
    channel_id: '',
    begin_pubdate: '',
    end_pubdate: '',
    page: 1,
    pagesize: 10
  })
  // 文章数量
  const [count, setCount] = useState(0)
  //获取文章列表
  useEffect(() => {
    const getArticleList = async () => {
      // 调用接口
      const res = await articleGetListService(reqData)
      setArticleList(res.data.results)
      setCount(res.data.total_count)
    }
    getArticleList()
  }, [reqData])
  //表单提交
  const onFinish = (values) => {
    console.log(values)
    setReqData({
      ...reqData,
      status: values.status,
      channel_id: values.channel_id,
      begin_pubdate: values.date?.[0].format('YYYY-MM-DD') || '',
      end_pubdate: values.date?.[1].format('YYYY-MM-DD') || ''
    })
  }
  // 准备表格头部
  const [columns, setColumns] = useState([])
  //初始化表格头部
  useEffect(() => {
    //枚举状态
    const state = {
      1: <Tag color="yellow">{t('content.article.status.approving')}</Tag>,
      2: <Tag color="green">{t('content.article.status.pass')}</Tag>
    }
    //删除
    const handleDelete = async (id) => {
      await articleDeleteArticleService(id)
      setReqData({
        ...reqData
      })
    }
    setColumns([
      {
        title: t('content.article.columns.cover'),
        dataIndex: 'cover',
        width: 120,
        render: (cover) => {
          return (
            <img
              src={cover.images[0] || img404}
              width={80}
              height={60}
              alt=""
            />
          )
        }
      },
      {
        title: t('content.article.columns.title'),
        dataIndex: 'title',
        width: 220
      },
      {
        title: t('content.article.columns.status'),
        dataIndex: 'status',
        render: (data) => state[data]
      },
      {
        title: t('content.article.columns.pubdate'),
        dataIndex: 'pubdate'
      },
      {
        title: t('content.article.columns.read_count'),
        dataIndex: 'read_count'
      },
      {
        title: t('content.article.columns.comment_count'),
        dataIndex: 'comment_count'
      },
      {
        title: t('content.article.columns.like_count'),
        dataIndex: 'like_count'
      },
      {
        title: t('content.article.columns.operation'),
        render: (data) => {
          return (
            <Space size="middle">
              <Button
                type="primary"
                shape="circle"
                icon={<EditOutlined />}
                onClick={() => navigate(`/publish?id=${data.id}`)}
              />
              <Popconfirm
                title="删除文章"
                description="你确定要删除吗?"
                onConfirm={() => handleDelete(data.id)}
                okText="Yes"
                cancelText="No"
              >
                <Button
                  type="primary"
                  danger
                  shape="circle"
                  icon={<DeleteOutlined />}
                />
              </Popconfirm>
            </Space>
          )
        }
      }
    ])
  }, [t, reqData, navigate])
  //分页
  const onPageChange = (page) => {
    console.log(page)
    setReqData({
      ...reqData,
      page: page.current
    })
  }

  return (
    <div>
      <Card
        title={
          <Breadcrumb
            items={[
              {
                title: (
                  <Link to={'/'}>{t('content.article.breadCrumb.home')}</Link>
                )
              },
              { title: t('content.article.breadCrumb.article') }
            ]}
          />
        }
        style={{ marginBottom: 20 }}
      >
        <Form initialValues={{ status: '' }} onFinish={onFinish}>
          <Form.Item label={t('content.article.form.status')} name="status">
            <Radio.Group>
              <Radio value={''}>{t('content.article.form.all')}</Radio>
              <Radio value={0}>{t('content.article.form.draft')}</Radio>
              <Radio value={2}>{t('content.article.form.pass')}</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            label={t('content.article.form.channel')}
            name="channel_id"
          >
            <Select
              placeholder={t('content.article.form.channelPlaceholder')}
              defaultValue="推荐"
              style={{ width: 120 }}
            >
              {channelList.map((item) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item label={t('content.article.form.date')} name="date">
            {/* 传入locale属性 控制中文显示*/}
            <RangePicker
              locale={i18n.language === 'zh' ? locale : ''}
            ></RangePicker>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ marginLeft: 40 }}>
              {t('content.article.form.filter')}
            </Button>
          </Form.Item>
        </Form>

        {/*        */}
        <Card title={t('content.article.columns.count') + count}>
          <Table
            rowKey="id"
            columns={columns}
            dataSource={articleList}
            pagination={{
              total: count,
              pageSize: reqData.pagesize
            }}
            onChange={onPageChange}
          />
        </Card>
      </Card>
    </div>
  )
}

export default Article
